package com.dzb.langchain4j.controller;

import com.dzb.langchain4j.common.config.AiConfig;
import com.dzb.langchain4j.entity.ChatForm;
import dev.langchain4j.model.chat.ChatLanguageModel;
import dev.langchain4j.service.TokenStream;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

/**
 * @author: 418167
 * @CreateTime: 2025/06/01 00:00
 * @Description:
 */
@Slf4j
@Tag(name = "gscsd-ai")
@RestController
@RequestMapping("/ai")
public class AiController {

    @Autowired
    ChatLanguageModel qwenChatModel;

    @Operation(summary = "对话-all")
    @GetMapping(value = "/chat")
    public String chat(@RequestParam(value = "message"
            , defaultValue = "你是谁") String message) {
        return qwenChatModel.chat(message);
    }

    @Operation(summary = "对话-get")
    @GetMapping(value = "/chat/{message}")
    public String chatGet(@PathVariable("message") String message) {
        return qwenChatModel.chat(message);
    }

    @Operation(summary = "对话-post")
    @PostMapping(value = "/chatBody")
    public String chatBody(@RequestBody ChatForm chatForm) {
        return qwenChatModel.chat(chatForm.getMessage());
    }

    @Autowired
    AiConfig.AssistantAi assistant;

    @Operation(summary = "对话-aiConfig")
    @GetMapping(value = "/chatConfig")
    public String chatConfig(@RequestParam(value = "message", defaultValue = "你是谁") String message) {
        return assistant.chat(message);
    }


    @Operation(summary = "对话-aiConfigStream")
    @GetMapping(value = "/chatConfigStream", produces = "text/stream;charset=UTF-8")
    // @GetMapping(value = "/chatConfigStream", produces = MediaType.APPLICATION_STREAM_JSON_VALUE)
    public Flux<String> chatConfigStream(
            @RequestParam(value = "message", defaultValue = "你是谁") String message) {
        TokenStream stream = assistant.chatStream(message);

        return Flux.create(sink -> {
            stream.onPartialResponse(s -> {
                        sink.next(s);
                        log.info("===>>>partial response: {}", s);
                    })
                    .onCompleteResponse(c -> sink.complete())
                    .onError(sink::error)
                    .start();
        });
    }


}
